import hashlib
import logging

import requests

from .core import app
from flask import request, abort, g

from wechatpy import parse_message
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException
from wechatpy.messages import TextMessage, LocationMessage
from wechatpy.replies import BaseReply, TextReply
from .services import handle_request
from .settings import config

LOG = app.logger


@app.route('/wx', methods=['GET'])
def get_wx():
    signature = request.args['signature']
    timestamp = request.args['timestamp']
    nonce = request.args['nonce']
    echostr = request.args['echostr']
    token = config.weixin.token

    try:
        check_signature(token, signature, timestamp, nonce)
        return echostr
    except InvalidSignatureException as ex:
        return abort(400, "verify failed {}".format(ex))


@app.route('/wx', methods=['POST'])
def post_wx():
    data = request.data
    message = parse_message(data)

    g.message = message

    if isinstance(message, TextMessage):
        app.logger.info(u'接收到来自[%s]的消息：%s', message.source, message.target)
        content = handle_request(message, *filter(bool, message.content.split(' ')))
    elif isinstance(message, LocationMessage):
        app.logger.info(u'接收到来自[%s]的位置信息[%d, %d]', message.source, message.location_x, message.location_y)
        location_result = requests.get(u'http://api.map.baidu.com/geocoder/v2/', params={
            'location': '{},{}'.format(message.location_x, message.location_y),
            'output': 'json',
            'ak': config.baidu.map_ak
        }).json()
        location_components = location_result['result']['addressComponent']
        location = u'{}{}{}'.format(
            location_components['province'],
            location_components['city'] if location_components['province'] != location_components['city'] else u'',
            location_components['district']
        )

        LOG.info(u'用户{}的位置解析为{}', message.source, location)
        content = handle_request(message, u'报位置', location, message.location_y, message.location_x)
    else:
        content = '???'

    app.logger.info(u'响应为：%s', content)
    if isinstance(content, BaseReply):
        return content.render()
    else:
        return TextReply(message=message, content=content).render()

